package pers.cz.filter;

import pers.cz.menu.MenuService;
import pers.cz.model.Menu;
import pers.cz.model.Role;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 权限配置资源管理器
 * @program: springSecurity
 * @description: CustomSecurityMetadataSource
 * @author: Cheng Zhi
 * @create: 2021-04-17 23:06
 **/
@Service
public class CustomSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    Logger logger= LoggerFactory.getLogger(CustomSecurityMetadataSource.class);

    @Autowired
    MenuService testMenuService;

    private Map<String, Collection<ConfigAttribute>> resourceMap = null;

    // 路径匹配器
    private PathMatcher pathMatcher =  new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {

        String url = ((FilterInvocation)o).getRequestUrl();
        if (logger.isDebugEnabled()) {
            logger.debug("请求地址是：" + url);
        }

        List<Menu> menus = testMenuService.selectAllMenuByRole();
        for (Menu menu : menus) {
            if (pathMatcher.match(menu.getUrl(),url)) {

                String[] str = new String[menu.getRoles().size()];
                int i = 0;
                for (Role role : menu.getRoles()) {
                    String roleName = role.getRoleName();
                    str[i] = roleName;
                    i ++;
                }

                return SecurityConfig.createList(str);
            }
        }
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
